package com.crocodileQ.config;

import com.crocodileQ.filter.AuthenticationTokenFilter;
import com.crocodileQ.handler.security.AuthenticationEntryPointImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Slf4j
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private AuthenticationTokenFilter tokenFilter;
    @Autowired
    private AuthenticationEntryPointImpl authenticationEntryPoint;


    @Bean
    public PasswordEncoder getPasswordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
//
        http
//                关闭csrf
                .csrf().disable()
//                不通过Session获取SecurityContext
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                // 对于登录接口 允许匿名访问
//                .antMatchers("/login").anonymous()
//                .antMatchers("/logout").authenticated()
//                .antMatchers("/user/userInfo").authenticated()
////                拦截发送评论请求
//                .antMatchers("/comment").authenticated()
//                .antMatchers("/link/getAllLink").authenticated()
                //                除上面外的所有请求全部不需要进行认证
                .anyRequest().permitAll();

//        token 认证
            http.addFilterBefore(tokenFilter,UsernamePasswordAuthenticationFilter.class);

            http.logout().disable();
//        认证失败处理器

        http.exceptionHandling().authenticationEntryPoint(authenticationEntryPoint);

    }
}